"use strict";
const mongoose = require("mongoose");
const db = require("./index").db;
const fs = require("fs");
const path = require("path");
mongoose.Promise = global.Promise;


const initMongoose = function() {
    mongoose.connection.on("error", err => console.error("mongodb内部错误", err));
    mongoose.connection.on("connecting", () => console.log("正在连接mongodb"));
    mongoose.connection.on("connected", () => console.warn("mongodb 连接成功"));
    mongoose.connection.on("disconnected", () => console.warn("mongodb 失去连接，注意此时所有请求数据库的请求都被mogoose缓存了，因此看不到有请求进去的，因为么个请求都要经过session比较"));
    mongoose.connection.on("reconnected", () => console.warn("mongodb 重新连接成功"));
    mongoose.connect(db.url, db.options);
};

const initModel = function() {
  const models_path = path.normalize(__dirname + "/..") + "/models";
  fs.readdirSync(models_path).forEach(function(file) {
    require(models_path + "/" + file);
  });
};

const init = function() {
    initModel();
    initMongoose();
};

const getModel = function(name) {
    return mongoose.model(name);
};

const getConnection = function() {
    return mongoose.connection;
};


module.exports = {
    ObjectId: mongoose.Types.ObjectId,
    getModel,
    getConnection,
    init,
};
